package com.hotel.shiro;


import com.hotel.mapper.EmployeeMapper;
import com.hotel.pojo.Employee;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private EmployeeMapper employeeMapper;

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 从认证方法存入session的登录用户信息，取出来
        Employee employee = (Employee) SecurityUtils.getSubject().getSession().getAttribute("loginEmployee");
        // 拿到用户的角色
        String employePower = employee.getEmployePower();
        // 把用户的结果封装在 类中
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // 传入当前角色的名字
        simpleAuthorizationInfo.addRole(employePower);
        return simpleAuthorizationInfo;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 1、根据当前token信息，获取到待登录的用户名
        String employeeName = (String) token.getPrincipal();
        // 2、根据当前用户名查询出用户的信息
        Employee employee = employeeMapper.selectEmployeeByName(employeeName);
        // 3、判断当前查询出来的用户是否为null
        if (employee == null) {
            throw new UnknownAccountException("账号不存在    ");
        }
        try {
            // 把用户信息存入session
            SecurityUtils.getSubject().getSession().setAttribute("loginEmployee", employee);
        } catch (Exception e) {
            System.out.println("账号密码验证不通过");
        }
        // 4、查询出来了当前用户，进行密码的比对，主要返回一个对象
        // 参数：当前用户名、密码、盐、realm的名称
        // 5、获取盐
        ByteSource salt = ByteSource.Util.bytes(employeeName);
        return new SimpleAuthenticationInfo(employeeName, employee.getEmployePassword(), salt, getName());
    }
}
